import Taro, {Component} from '@tarojs/taro'
import {View, Picker, Text} from '@tarojs/components'
import {
  AtForm, AtInput, AtButton, AtSwitch,
  AtImagePicker, AtList, AtListItem, AtTextarea
} from 'taro-ui'
import fetch from '../../utils/request'
import {
  API_GOODS_CATE,
  API_GOODS_BRAND,
  API_GOODS_TAG,
  API_COMM_UPLOAD,
  API_GOODS_PRODUCT_ADD,
  API_GOODS_PRODUCT_INFO,
  API_GOODS_PRODUCT_UPDATE
} from '../../constants/api'
import classNames from 'classnames'
import {s_to_hs} from '../../utils/comman'
import './index.scss'
import {connect} from "_@tarojs_redux@2.2.13@@tarojs/redux";
import * as productActions from "../../actions/product";
import * as wxActions from "../../actions/wx";

const CharSPLIT = 'η';

@connect(state => ({...state.wx}), {...wxActions})
class Operate extends Component {
  state = {
    cates: [],
    brands: [],
    tags: [],
    sexes: [
      {name: '男女同款', id: 3},
      {name: '男款', id: 1},
      {name: '女款', id: 2},
    ],
    formValue: {
      name: '',
      summary: '',
      brandName: '',
      brandIndex: '',
      sexIndex: 0,
      sexName: '男女同款',
      cateName: '',
      bannerImage: {},
      video: {},
      files: [],
      cateIndex: -1,
      tagName: '',
      status: true,
      keyword: '',
      banner: false
    },
    loading: false
  }

  static options = {
    addGlobalClass: true
  }

  config = {
    navigationBarTitleText: ''
  }

  componentWillMount() {
  }

  componentDidMount() {
  }

  componentDidShow() {
    const {params} = this.$router
    console.log("params", params)
    if (Number(params.id) > 0) {
      Taro.setNavigationBarTitle({
        title: '编辑商品'
      })
    } else {
      Taro.setNavigationBarTitle({
        title: '上传商品'
      })
    }
    Promise.all([
      this.getCates(),
      this.getBrands(),
      this.getTags()
    ]).then(_ => {
      if (Number(params.id) > 0) {
        this.getInfo(Number(params.id))
      }
    })
  }

  async getInfo(id) {
    let info = await fetch({
      url: API_GOODS_PRODUCT_INFO,
      payload: {
        id
      }
    })
    let {cates, brands, sexes} = this.state
    let {name, tags, bannerImage, video, brandId, cateId, summary, files, sex, keyword, status, banner} = info
    let cateIndex = cates.findIndex(item => item.id == cateId)
    let cateName = cateIndex > -1 ? cates[cateIndex].name : ''
    let brandIndex = brands.findIndex(item => item.id == brandId)
    let brandName = brandIndex > -1 ? brands[brandIndex].name : ''
    let sexIndex = sexes.findIndex(item => item.id == sex)
    let sexName = sexName > -1 ? sexes[sexIndex].name : ''
    if (bannerImage && bannerImage.url) {
      bannerImage.url = bannerImage.url.replace(LOGO_SPLIT, '') + LOGO_JPG_SPLIT
    } else {
      bannerImage = {}
    }
    if (files) {
      files = files.map(item => {
        item.url = item.url.replace(DETAIL_SPLIT, '') + DETAIL_JPG_SPLIT
        return item
      })
    }
    let formValue = {
      ...this.state.formValue,
      bannerImage,
      name,
      sexIndex,
      sexName,
      cateIndex,
      cateName,
      brandIndex,
      brandName,
      video: video ? video : {},
      summary,
      files,
      keyword: keyword ? keyword.replace(CharSPLIT, '、') : '',
      tagName: tags ? tags.join('、') : '',
      status: status == 1 ? true : false,
      banner: banner == 1 ? true : false,
    }
    this.setState({formValue}, () => {
      console.log(this.state.formValue)
    })
  }

  componentDidHide() {
  }

  componentCatchError() {
  }

  async getCates() {
    let cates = await fetch({
      url: API_GOODS_CATE,
      payload: {}
    })
    this.setState({
      cates
    })
    return cates
  }

  async getBrands() {
    let brands = await fetch({
      url: API_GOODS_BRAND,
      payload: {}
    })
    this.setState({
      brands: [...brands]
    })
    return brands
  }

  async getTags() {
    let tags = await fetch({
      url: API_GOODS_TAG,
      payload: {}
    })
    this.setState({
      tags: [...tags]
    })
    return tags
  }


  nameChange(name) {
    let formValue = {
      ...this.state.formValue,
      name
    }
    this.setState({
      formValue
    })
  }

  summaryChange(summary) {
    let formValue = {
      ...this.state.formValue,
      summary
    }
    this.setState({
      formValue
    })
  }

  onSubmit(event) {
    console.log('formValue', this.state.formValue)
    const {formValue, cates, brands, loading, sexes} = this.state
    const {userInfo} = this.props
    if (loading) {
      return;
    }
    let {
      bannerImage,
      name,
      cateIndex,
      summary,
      brandIndex,
      tagName,
      video,
      files,
      status,
      sexIndex,
      keyword,
      banner
    } = formValue
    if (!name) {
      Taro.showToast({
        title: '请填写名称',
        icon:'none'
      })
      return
    }
    if (!summary) {
      Taro.showToast({
        title: '请填写描述',
        icon:'none'
      })
      return
    }
    if (!bannerImage.url) {
      Taro.showToast({
        title: '请上传封面',
        icon:'none'
      })
      return;
    }
    if(cateIndex < 0){
      Taro.showToast({
        title: '请选择分类',
        icon:'none'
      })
      return;
    }
    try {
      bannerImage.url = bannerImage.url.replace(LOGO_JPG_SPLIT, '')
      this.setState({loading: true}, async () => {
        try {
          let payload = {
            name,
            summary,
            brandId: Number(brandIndex) >= 0 ? brands[Number(brandIndex)].id : '',
            cateId: Number(cateIndex) >= 0 ? cates[Number(cateIndex)].id : '',
            sex: Number(sexIndex) >= 0 ? sexes[Number(sexIndex)].id : '',
            tags: tagName.split('、').join(CharSPLIT),
            keyword: keyword.split('、').join(CharSPLIT),
            bannerImage: JSON.stringify(bannerImage),
            files: JSON.stringify(
              files.map(item => {
                item.url = item.url.replace(DETAIL_JPG_SPLIT, '')
                return item
              })
            ),
            video: JSON.stringify(video),
            status: status ? 1 : 0,
            banner: banner ? 1 : 0
          }
          let url = Number(this.$router.params.id) > 0 ? API_GOODS_PRODUCT_UPDATE : API_GOODS_PRODUCT_ADD
          if (Number(this.$router.params.id) > 0) {
            payload.id = this.$router.params.id
          }
          await fetch({
            url,
            method: 'POST',
            payload
          })
          Taro.showToast({
            title: '操作成功'
          })
          let f = {
            ...formValue,
            name: '',
            summary: '',
            brandName: '',
            brandIndex: '',
            cateName: '',
            bannerImage: {},
            video: {},
            files: [],
            cateIndex: -1,
            tagName: '',
            status: true,
            keyword: '',
            sexIndex: 0,
            sexName: '男女同款',
            banner: false
          }
          this.setState({formValue: f})
          this.setState({loading: false})
          if (payload.id) {
            Taro.navigateBack()
          }
        } catch (e) {
          this.setState({loading: false})
        }
      })
    } catch (err) {
      this.setState({loading: false})
    }
  }

  fileChange(event, type) {
    console.log('event', event)
    console.log('type', type)
  }

  async bannerImageChange(event, type) {
    console.log('event', event)
    console.log('type', type)
    let formValue
    switch (type) {
      case 'add':
        Taro.showLoading({
          title: '上传中',
          mask: true
        })
        Taro.uploadFile({
          url: API_COMM_UPLOAD,      //此处换上你的接口地址
          filePath: event[event.length - 1].url,
          name: 'img',
          header: {
            "Content-Type": "multipart/form-data"
          },
          formData: {}
        }).then(res => {
          if (JSON.parse(res.data).code != 1000) {
            Taro.showToast({
              title: '上传失败',
              icon: 'none'
            })
            return;
          }
          console.log('上传成功', res)
          let b = JSON.parse(res.data).data
          if (Object.prototype.toString.call(b) === '[object Object]' && b['url']) {
            let url = b.url + LOGO_JPG_SPLIT
            b = {...b, url}
            console.log('b', b)
            console.log('burl', b.url)
          }
          formValue = {
            ...this.state.formValue,
            bannerImage: b
          }
          this.setState({formValue}, () => {
            console.log('formValue', this.state.formValue)
          })
          Taro.showToast({
            title: '上传成功'
          })
        }).catch(err => {
          console.log('上传失败', err)
          Taro.showToast({
            title: '上传失败',
            icon: 'none'
          })
        })
        break;
      default:
        formValue = {
          ...this.state.formValue,
          bannerImage: {}
        }
        this.setState({formValue})
        break;
    }


  }

  async filesChange(event, type) {
    let newFiles = []
    switch (type) {
      case 'add':
        newFiles = event.filter(item => item.file)
        let errIndexArr = []
        console.log('newFiles', newFiles)
        newFiles.forEach((item, index) => {
          Taro.uploadFile({
            url: API_COMM_UPLOAD,      //此处换上你的接口地址
            filePath: item.url,
            name: 'img',
            header: {
              "Content-Type": "multipart/form-data"
            },
            formData: {}
          }).then(res => {
            if (JSON.parse(res.data).code != 1000) {
              Taro.showToast({
                title: '上传失败',
                icon: 'none'
              })
              return;
            }
            let files = this.state.formValue.files
            let b = JSON.parse(res.data).data
            let url = b.url + DETAIL_JPG_SPLIT
            b = {...b, url}
            files.push(b)
            let formValue = {
              ...this.state.formValue,
              files
            }
            this.setState({formValue})
          }).catch(err => {
            errIndexArr.push(index)
          })
        })
        // let files2 = this.state.formValue.files.filter((op,idx)=>!errIndexArr.includes(idx))
        // let formValue3 = {
        //   ...this.state.formValue,
        //   files:files2
        // }
        // this.setState({formValue:formValue3})
        break;
      default:
        Taro.showLoading({
          title: '',
          mask: true
        })
        let formValue2 = {
          ...this.state.formValue,
          files: event
        }
        console.log('event', event)
        console.log('type', type)
        this.setState({formValue: formValue2}, () => {
          Taro.hideLoading()
        })
        break;
    }
  }


  cateChange(e) {
    console.log('cate', e)
    let cateIndex = e.detail.value
    let formValue = {
      ...this.state.formValue,
      cateIndex,
      cateName: this.state.cates[cateIndex].name
    }
    this.setState({
      formValue
    }, () => {
      console.log('formValue', this.state.formValue)
    })
  }

  sexChange(e) {
    let sexIndex = e.detail.value
    let formValue = {
      ...this.state.formValue,
      sexIndex,
      sexName: this.state.sexes[sexIndex].name
    }
    this.setState({
      formValue
    }, () => {
      console.log('formValue', this.state.formValue)
    })
  }

  brandChange(e) {
    let brandIndex = e.detail.value
    let formValue = {
      ...this.state.formValue,
      brandIndex,
      brandName: this.state.brands[brandIndex].name
    }
    this.setState({
      formValue
    }, () => {
      console.log('formValue', this.state.formValue)
    })
  }

  tagChange(tagName) {
    // let tagIndex = e.detail.value
    // let formValue = {
    //   ...this.state.formValue,
    //   tagIndex,
    //   tagName:this.state.tags[tagIndex].name
    // }
    // this.setState({
    //   formValue
    // },()=>{
    //   console.log('formValue', this.state.formValue)
    // })
    let formValue = {
      ...this.state.formValue,
      tagName
    }
    this.setState({
      formValue
    })
  }

  keywordChange(keyword) {
    let formValue = {
      ...this.state.formValue,
      keyword
    }
    this.setState({
      formValue
    })
  }

  uploadVideo() {
    Taro.chooseVideo({
      sourceType: ['album', 'camera'
        /** 使用相机拍摄视频 */],
      maxDuration: 60,
      camera: 'back',
      success: (res) => {
        console.log('video', res)
        Taro.showLoading({
          title: '上传中',
          mask: true
        })
        Taro.uploadFile({
          url: API_COMM_UPLOAD,      //此处换上你的接口地址
          filePath: res.tempFilePath,
          name: 'img',
          header: {
            "Content-Type": "multipart/form-data"
          },
          formData: {}
        }).then(res => {
          console.log('上传成功', res)
          console.log('上传成功', this.state.formValue)
          let formValue = {
            ...this.state.formValue,
            video: JSON.parse(res.data).data
          }
          this.setState({formValue}, () => {
            console.log('formValue', this.state.formValue)
          })
          Taro.hideLoading()
          Taro.showToast({
            title: '上传成功'
          })
        }).catch(err => {
          Taro.hideLoading()
          Taro.showToast({
            title: '上传失败'
          })
        })
      }
    })
  }


  seeVideo() {
    Taro.previewImage({
      urls: [this.state.formValue.video.url],
      current: 0
    })
  }


  deleteVideo() {
    let formValue = {
      ...this.state.formValue,
      video: {}
    }
    this.setState({formValue})
  }

  statusChange(status) {
    let formValue = {
      ...this.state.formValue,
      status
    }
    this.setState({formValue})
  }

  bannerChange(banner) {
    let formValue = {
      ...this.state.formValue,
      banner
    }
    this.setState({formValue})
  }

  render() {
    const {formValue, cates, brands, tags, loading, sexes} = this.state
    const {
      bannerImage, name, cateName, cateIndex, summary, status, sexIndex, sexName, keyword,
      brandName, brandIndex, tagIndex, tagName, video, files, banner
    } = formValue
    return (
      <View className="operate_page">
        <AtForm
          onSubmit={this.onSubmit.bind(this)}
        >
          {/* <View className="form_row"> */}
          <View className="form_item">
            <View className="form_label">封面</View>
            <View className={classNames('form_control', {'empty_avator': !(bannerImage && bannerImage.url)})}>
              <AtImagePicker
                files={[bannerImage]}
                onChange={this.bannerImageChange.bind(this)}
                multiple={false}
                count={1}
              />
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">视频</View>
            <View className="form_control">
              {/* <AtImagePicker
                  files={[video]}
                  onChange={this.videoChange.bind(this)}
                  multiple={false}
                  count={1}
                /> */}
              <AtButton type='secondary' size='small'
                        onClick={this.uploadVideo.bind(this)}>上传视频</AtButton>
              {
                video && video.url &&
                <View className="form_video-wrapper">
                  <View className="detail__page-banner">

                    <View
                      className={classNames('recommend_box_vedio_item')}
                    >
                      <Image
                        className="recommend_box_vedio_item-img"
                        src={video.url + VIDEO_SUFFIX}
                        mode="aspectFill"
                        lazyLoad
                        webp
                      />
                      <View className="recommend_box_vedio_item-button">
                        <Text className="at-icon at-icon-play">

                        </Text>
                        <Text>
                          {s_to_hs(video.avinfo ? video.avinfo.video.duration : 0)}
                        </Text>
                      </View>
                    </View>

                  </View>

                  <View className='at-icon at-icon-subtract-circle' onClick={this.deleteVideo.bind(this)}></View>
                </View>

              }
            </View>
          </View>
          {/* </View> */}
          <View className="form_item">
            <View className="form_label">标题</View>
            <View className="form_control">
              <AtInput
                type='text'
                placeholder='标题'
                value={name}
                onChange={this.nameChange.bind(this)}
              />
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">性别</View>
            <View className="form_control">
              <Picker mode='selector' range={sexes} rangeKey="name"
                      onChange={this.sexChange.bind(this)} value={sexIndex}>
                <AtList>
                  <AtListItem
                    title='性别'
                    extraText={sexName}
                  />
                </AtList>
              </Picker>
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">分类</View>
            <View className="form_control">
              <Picker mode='selector' range={cates} rangeKey="name"
                      onChange={this.cateChange.bind(this)} value={cateIndex}>
                <AtList>
                  <AtListItem
                    title='分类'
                    extraText={cateName}
                  />
                </AtList>
              </Picker>
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">品牌</View>
            <View className="form_control">
              <Picker mode='selector' range={brands} rangeKey="name"
                      onChange={this.brandChange.bind(this)} value={brandIndex}>
                <AtList>
                  <AtListItem
                    title='品牌'
                    extraText={brandName}
                  />
                </AtList>
              </Picker>
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">关键字</View>
            <View className="form_control">
              <AtInput
                type='text'
                placeholder='关键字，用、隔开'
                value={keyword}
                onChange={this.keywordChange.bind(this)}
              />
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">标签</View>
            <View className="form_control">
              {/* <Picker mode='selector' range={tags}  rangeKey="name"
              onChange={this.tagChange.bind(this)} value={tagIndex}>
                  <AtList>
                    <AtListItem
                      title='标签'
                      extraText={tagName}
                    />
                  </AtList>
              </Picker> */}
              <AtInput
                type='text'
                placeholder='标签，用、隔开'
                value={tagName}
                onChange={this.tagChange.bind(this)}
              />
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">状态</View>
            <View className="form_control switch_control">
              <AtSwitch border={false}
                        checked={status} onChange={this.statusChange.bind(this)}/>
              <Text className={status ? 'text-success' : 'text-error'}>{status ? '上架中' : '已下架'}</Text>
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">轮播</View>
            <View className="form_control switch_control">
              <AtSwitch border={false}
                        checked={banner} onChange={this.bannerChange.bind(this)}/>
              <Text className={banner ? 'text-success' : 'text-error'}>{banner ? '是' : '否'}</Text>
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">描述</View>
            <View className="form_control">
              <AtTextarea
                placeholder='描述'
                value={summary}
                maxLength={2000}
                height={300}
                onChange={this.summaryChange.bind(this)}
              />
            </View>
          </View>
          <View className="form_item">
            <View className="form_label">图片</View>
            <View className={classNames('form_control', 'files-picker')}>
              <AtImagePicker
                files={files}
                onChange={this.filesChange.bind(this)}
                multiple={true}
                count={99}
                length={3}
              />
            </View>
          </View>

          <AtButton loading={loading}
                    formType='submit' type='primary' size='small' className="submit_button">提交</AtButton>
        </AtForm>
      </View>
    )
  }
}

export default Operate
